//
//  UserModel.m
//  BMHeadLine
//
//  Created by 徐益智 on 16/1/18.
//  Copyright © 2016年 Vdianjing. All rights reserved.
//

#import "UserModel.h"

#import "VDJConstant.h"
#import <objc/runtime.h>
#import <UIKit/UIKit.h>

#define kFilePath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"user.data"]

@implementation UserModel
/**
 *  编码
 */
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i ++) {
        Ivar ivar = ivars[i];
        const char *name = ivar_getName(ivar);
        NSString *key = [NSString stringWithUTF8String:name];
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
    free(ivars);
}

/**
*  解码
*/
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        if (aDecoder == nil) {
            return self;
        }
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([self class], &count);
        for (int i = 0;i < count; i ++) {
            Ivar ivar = ivars[i];
            const char *name = ivar_getName(ivar);
            NSString *key = [NSString stringWithUTF8String:name];
            id value = [aDecoder decodeObjectForKey:key];
            [self setValue:value forKey:key];
        }
        free(ivars);
    }
    return self;
}

- (void)save
{
    [NSKeyedArchiver archiveRootObject:self toFile:kFilePath];
}

+ (UserModel *)queryModel
{
    UserModel * model = [NSKeyedUnarchiver unarchiveObjectWithFile:kFilePath];
    return model;
}

/**
 *删除 DocumentDirectory 所有文件
 */
+ (void)deleteAllFile
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSAllDomainsMask, YES) objectAtIndex:0];
    NSDirectoryEnumerator* en = [fileManager enumeratorAtPath:documentsDirectory];
    NSError* err = nil;
    BOOL res;
    
    NSString* file;
    while (file = [en nextObject])
    {
        res = [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:file] error:&err];
        if (!res && err) {
            MyLog(@"oops: %@", err);
        }
    }
}

+ (void)deleteUserInfoFile
{
    NSFileManager *fileManeger = [NSFileManager defaultManager];
    BOOL isEx = [fileManeger fileExistsAtPath:kFilePath];
    
    if (isEx) {
        [fileManeger removeItemAtPath:kFilePath error:nil];
    }else {
        MyLog(@"%@路径文件不存在", kFilePath);
    }
}

@end
